package cn.uestc.labhms.modules.hms.exception;

import cn.uestc.labhms.common.utils.R;
import cn.uestc.labhms.modules.hms.param.BizCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * hms全局异常处理
 */
@Slf4j
//@RestControllerAdvice(basePackages = "cn.uestc.labhms.modules.hms.controller")
@RestControllerAdvice
public class HMSExceptionAdvice {
    /**
     * 数据校验异常
     * @param e JSR-303校验抛出异常
     * @return 出错信息
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("数据校验出现异常：{}，异常类型：{}", e.getMessage(), e.getClass());
        e.printStackTrace();
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        fieldErrors.forEach((item) -> {
            map.put(item.getField(), item.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data", map);
    }
    /**
     * 数据校验异常
     * @param e JSR-303校验抛出异常
     * @return 出错信息
     */
    @ExceptionHandler(value = BindException.class)
    public R handleValidException(BindException e) {
        log.error("数据校验出现异常：{}，异常类型：{}", e.getMessage(), e.getClass());
        e.printStackTrace();
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        fieldErrors.forEach((item) -> {
            map.put(item.getField(), item.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data", map);
    }
    /**
     * hms异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = HMSException.class)
    public R handleHmsException(HMSException e) {
        log.error("异常：{}，异常类型：{}", e.getMessage(), e.getClass());
        e.printStackTrace();
        return R.error(e.getCode(), e.getMsg());
    }

    /**
     * 不可知异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable e) {
        log.error("异常：{}，异常类型：{}", e.getMessage(), e.getClass());
        e.printStackTrace();
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(), BizCodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }
}
